package org.nf.servlet;

import com.google.gson.Gson;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.nf.User;
import org.nf.UserService;
import org.nf.util.GsonUtil;
import org.nf.vo.ResponseData;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * @author zhu
 * @date 2024-04-25
 */
@WebServlet("/allUsers")
public class ShowAllUserServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf-8");
        resp.setCharacterEncoding("utf-8");

        UserService userService = new UserService();
        List<User> userList = userService.findAllUsers();
        ResponseData responseData = new ResponseData();

        if(userList != null){
            responseData.setCode(200);
            responseData.setMsg("成功");
            responseData.setData(userList);
        }else {
            responseData.setCode(500);
            responseData.setMsg("失败");
        }

        // 把数据序列化为 JSON 字符串返回
        String json = GsonUtil.toJson(responseData);

        // 把数据响应输出到客户端浏览器中
        PrintWriter out = resp.getWriter();
        out.println(json);

        out.flush();
        out.close();
    }
}
